package com.zwcl.common.web.sign;

import com.zwcl.common.core.utils.JsonUtils;
import com.zwcl.common.core.utils.MD5Utils;
import com.zwcl.common.core.utils.ObjectMapUtil;
import com.zwcl.common.web.domain.SignRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.*;

@Slf4j
public class SignRequestTest {

    private static String appId="php";
    private static String appKey="sdfdfgjj";

    public static void main(String[] args) {
        Map<String,Object > reqParameter = new HashMap<>();
        reqParameter.put("transactionNo","10312000007");
        reqParameter.put("sourceFrom","KBB");
        Map<String,Object > reqMap = commonParameter(reqParameter);
        StringBuilder data=getData(reqMap).append("?key=").append(appKey);
        String sign= MD5Utils.md5Hex(data.toString());
        reqMap.put("sign", sign);
        log.info("取消订单接口：{}",JsonUtils.objectToJson(reqMap));
    }

    /***
     * 公共请求参数组装
     * @return
     */
    public static Map<String,Object > commonParameter(Map<String,Object > reqParameter){
        SignRequest signRequest=new SignRequest();
        signRequest.setAppId(appId);
        signRequest.setTimestamp(System.currentTimeMillis());
        // 组装请求参数
        try {
            signRequest.setRequestData(Base64.getEncoder().encodeToString(JsonUtils.objectToJson(reqParameter).getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  ObjectMapUtil.bean2Map(signRequest);
    }

    public static StringBuilder getData(Map<String, Object> map) {
        map.remove("sign");
        List<Map.Entry<String, Object>> infoIds = new ArrayList<>(map.entrySet());
        // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
        Collections.sort(infoIds, new Comparator<Map.Entry<String, Object>>() {
            @Override
            public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                return (o1.getKey()).compareTo(o2.getKey());
            }
        });
        // 构造签名键值对的格式
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> item : infoIds) {
            if (StringUtils.isNoneBlank(item.getKey())) {
                String key = item.getKey();
                Object val = item.getValue();
                if (ObjectUtils.isNotEmpty(val)) {
                    sb.append(key + "=" + val + "&");
                }
            }
        }
        return sb;
    }


}
